package org.sys.transporttrainsys.controller;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.sys.transporttrainsys.service.ReportService;
import org.sys.transporttrainsys.dto.ExamStatistics;
import org.sys.transporttrainsys.entity.StudentExamStatus;
import org.sys.transporttrainsys.service.StudentExamStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.List;

@RestController
@CrossOrigin(origins = "http://localhost:5173")
@RequestMapping("/api/exam-status")
public class StudentExamStatusController {

    @Autowired
    private StudentExamStatusService service;

    @Autowired
    private ReportService reportService;

    @GetMapping
    public List<StudentExamStatus> getAllExamStatuses() {
        return service.getAllExamStatuses(); // 返回所有学员考试情况
    }

    @GetMapping("/student/{id}")
    public List<StudentExamStatus> getByStudentId(@PathVariable Long id) {
        return service.getByStudentId(id); // 根据学员ID查询
    }

    @GetMapping("/exam/{id}")
    public List<StudentExamStatus> getByExamId(@PathVariable Long id) {
        return service.getByExamId(id); // 根据考试ID查询
    }

    @GetMapping("/statistics")
    public List<ExamStatistics> getStatistics() {
        return service.getStatistics(); // 返回统计结果
    }

    @GetMapping("/report")
    public ResponseEntity<FileSystemResource> generateReport() {
        // 生成报表
        List<ExamStatistics> statistics = service.getStatistics();
        String fileName = "ExamStatisticsReport.xlsx"; // 报表文件名
        reportService.generateExcelReport(statistics, fileName); // 生成报表

        // 创建文件资源以供下载
        File file = new File(fileName);
        FileSystemResource resource = new FileSystemResource(file);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());

        return new ResponseEntity<>(resource, headers, HttpStatus.OK); // 返回报表
    }

    @GetMapping("/export")
    public ResponseEntity<byte[]> exportExamStatuses() {
        List<StudentExamStatus> statuses = service.getAllExamStatuses();

        // 创建 Excel 文档
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("学员考试情况");

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("ID");
        headerRow.createCell(1).setCellValue("学员姓名");
        headerRow.createCell(2).setCellValue("考试名称");
        headerRow.createCell(3).setCellValue("得分");
        headerRow.createCell(4).setCellValue("考试结果");

        // 填充数据
        int rowNum = 1;
        for (StudentExamStatus status : statuses) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(status.getId());
            row.createCell(1).setCellValue(status.getStudent().getName());
            row.createCell(2).setCellValue(status.getExam().getName());
            row.createCell(3).setCellValue(status.getExamRecordScore());

            // 计算考试结果
            Integer score = status.getExamRecordScore(); // 从考试记录获取分数
            Integer totalScore = status.getExam().getTotalScore(); // 获取考试总分
            String result = (score >= 0.6 * totalScore) ? "通过" : "未通过"; // 计算结果
            row.createCell(4).setCellValue(result); // 将结果写入 Excel
        }

        // 将工作簿写入字节数组输出流
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            workbook.write(outputStream);
            workbook.close();

            byte[] bytes = outputStream.toByteArray();

            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=exam_statuses.xlsx");

            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}